package com.wcg.javabean;

import com.wcg.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class LogAop {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SysLogService sysLogService;

    private Date visitTime; // 开始时间

    // 前置通知：记录访问开始时间
    @Before("execution(* com.wcg.controller.*.*(..))")
    public void doBefore(JoinPoint jp) {
        visitTime = new Date(); // 设置访问开始时间
    }

    // 后置通知：记录日志信息
    @After("execution(* com.wcg.controller.*.*(..))")
    public void doAfter(JoinPoint jp) throws Exception {
        long time = new Date().getTime() - visitTime.getTime(); // 访问时长
        String className = jp.getTarget().getClass().getSimpleName(); // 类名
        String methodName = jp.getSignature().getName(); // 方法名
        Object[] args = jp.getArgs(); // 方法参数

        // 获取URL和IP
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();
        ip = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;

        // 获取用户信息
        User user = (User) request.getSession().getAttribute("user");
        String username = user != null ? user.getUsername() : "anonymous";

        // 构建日志对象
        SysLog sysLog = new SysLog();
        sysLog.setExecutionTime(time);
        sysLog.setIp(ip);
        sysLog.setClassName(className);
        sysLog.setMethodName(methodName);
        sysLog.setArgs(Arrays.toString(args));
        sysLog.setUrl(url);
        sysLog.setUsername(username);
        sysLog.setVisitTime(visitTime);

        // 保存日志
        sysLogService.add(sysLog);
    }
}
